package com.tacademy.jmtwitter;

import java.net.URL;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.OAuthException;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class Authorize extends Activity {
	public static final String SAVE = "save";
	public static final String TOKEN = "Token";
	public static final String SECRET = "Secret";
	final static int REQUEST_B = 1;
	public static final int OAUTH_START = 1;
	public static final int OAUTH_COMPLETE = 2;
	public static final long OAUTH_SUCCESS = 1;
	public static final long OAUTH_FAIL = 2;
	final static String EXTRA1_STRING = "EXTRA1";
	final static String EXTRA2_STRING = "EXTRA2";
	final static String EXTRA3_STRING = "EXTRA3";
	final static String EXTRA4_STRING = "EXTRA4";
	CommonsHttpOAuthConsumer mConsumer;
	CommonsHttpOAuthProvider mProvider;
	OauthTask mTask;
	ProgressBar mProgress;
	User mUser;
	Intent mIntent;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		Log.d("Authorize", "온크리에이트");
		setContentView(R.layout.activity_start);
		mProgress = (ProgressBar) findViewById(R.id.progressBarMain);
		
	}
	@Override
	protected void onStart() {
		Log.d("Authorize", "온스타트");
		super.onStart();
		Log.d("jmkkk", "알람 캔슬");
		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		Intent intent = new Intent(this, NotificationService.class);
		PendingIntent operation = PendingIntent.getService(this, 0, intent, 0);
		am.cancel(operation);
		
	}
	@Override
	protected void onStop() {
		Log.d("Authorize", "온스탑");	
		super.onStop();
	}
	@Override
	protected void onResume() {
		Log.d("Authorize", "온리점");
		super.onResume();
		mProgress.setVisibility(View.INVISIBLE);
	}

	public void onClick(View v) {
		mProgress.setVisibility(View.VISIBLE);
		mTask = new OauthTask();
		mTask.execute();
	}

	void startOauth() {
		mConsumer = new CommonsHttpOAuthConsumer(TwitterApi.CONSUMER_KEY,
				TwitterApi.CONSUMER_SECRET);
		mProvider = new CommonsHttpOAuthProvider(TwitterApi.REQUEST_TOKEN_URL,
				TwitterApi.ACCESS_TOKEN_URL, TwitterApi.AUTHORIZE_URL);

		String authUrl;
		try {
			authUrl = mProvider.retrieveRequestToken(mConsumer,
					TwitterApi.CALLBACK_URL);

			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
		} catch (OAuthException e) {
			Log.e("tc", "OAuthException:" + e.getMessage());
			e.printStackTrace();
		}
	}

	// /android:launchMode="singleTask" 일 경우 ////////////////////
	@Override
	protected void onNewIntent(Intent intent) {
		Log.d("Authorize", "onNewIntent");
		super.onNewIntent(intent);
		Uri uri = intent.getData();
		if (uri == null) {
			return;
		}
		try {
			String verifier = uri.getQueryParameter("oauth_verifier"); // twit://twitlecture.com/?oauth_verifier=alsdfjalsdjf;ljas
			mProvider.retrieveAccessToken(mConsumer, verifier);
			String accessToken = mConsumer.getToken();
			String accessTokenSecret = mConsumer.getTokenSecret();
			Log.d("tc", "AccessToken: " + accessToken
					+ ", AccessTokenSecret : " + accessTokenSecret);
			// SharedPreference잘 저장!@!@
			savePreference("Token", accessToken);
			savePreference("Secret", accessTokenSecret);

		} catch (OAuthException e) {
			Log.e("tc", "OAuthException" + e.getMessage());
		}
	}

	class OauthTask extends AsyncTask<URL, Integer, Long> {

		@Override
		protected Long doInBackground(URL... params) {
			// background
			// sharedPreference에 AccessToken이 없을때 startOauth()
			// AccessToken이 없다
			TwitterApi api = new TwitterApi(readPreference(TOKEN),
					readPreference(SECRET));
			
			mUser = api.verifyCredentials();
			Log.d("Authorize", "verifyCredentials 시작함");
			if (mUser == null) {
				Log.d("Authorize", "유저값 null임");
				publishProgress(OAUTH_START);
				onCancelled();
				startOauth();
				// /onPostExecute(result)로 결과값 보내서 실행
				
				return OAUTH_FAIL;
			}
			Log.d("Authorize", "성공 일 경우");
			return OAUTH_SUCCESS;
		}

		@Override
		protected void onPreExecute() {
			// doInBackground 전에 excute를 호출한 thread에서 실행
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Long result) {
			// doInBackground 실행뒤 main에서 실행
			super.onPostExecute(result);
			if (OAUTH_FAIL == result) {

			} else if (OAUTH_SUCCESS == result) {
				String name = mUser.getName();
				Log.d("Authorize", "Intent 시작" + name);
				mIntent = new Intent(Authorize.this,
						JMTwitterActivity.class);
				mIntent.putExtra(EXTRA1_STRING, readPreference(TOKEN));
				mIntent.putExtra(EXTRA2_STRING, readPreference(SECRET));
				mIntent.putExtra(EXTRA3_STRING, name);
				publishProgress(OAUTH_COMPLETE);
				startActivityForResult(mIntent, REQUEST_B);// 타임라인 액티비티 띠우기
				Log.d("Authorize", "startActivityForResult(mIntent, REQUEST_B);");
			}

		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			switch (values[0]) {
			case 1:
				// mProgress.setVisibility(View.INVISIBLE);
				Toast.makeText(Authorize.this, "인증합니다", Toast.LENGTH_SHORT)
						.show();
				break;
			case 2:
				Toast.makeText(Authorize.this, "인증완료 잠시만 기다리세요!",
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}

			// // values[0];
			// values.length;
		}
	}

	// ///////////////savePreference
	public void savePreference(String key, String value) {
		SharedPreferences pref = getSharedPreferences(SAVE, MODE_PRIVATE);
		SharedPreferences.Editor edit = pref.edit();
		edit.putString(key, value);
		edit.commit();
		Log.d("Authorize", "savePreferenceCommit");
	}

	public String readPreference(String key) {
		SharedPreferences pref = getSharedPreferences(SAVE, MODE_PRIVATE);
		String v = pref.getString(key, null);
		Log.d("Authorize", "read" + v);
		return v;

	}

}
